#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <sys/wait.h>
#include <fcntl.h>

void split(char **args, char *input)
{
    char *token = strtok(input, " ");
    int i = 0;
    while (token != NULL)
    {
        args[i++] = token;
        token = strtok(NULL, " ");
    }
    args[i] = NULL;
}

int main()
{
    // 自动生成测试文件
    int fd = open("shell_test.txt", O_WRONLY | O_CREAT, 0644);
    write(fd, "Shell test file\n", 16);
    close(fd);

    char input[100];
    char *args[10];
    while (1)
    {
        printf("myshell> ");
        fgets(input, sizeof(input), stdin);
        input[strlen(input) - 1] = '\0'; // 去掉换行符
        if (strcmp(input, "#") == 0)
            break;
        split(args, input);
        pid_t pid = fork();
        if (pid == 0)
        {
            execvp(args[0], args);
            perror("execvp failed");
            exit(1);
        }
        else
        {
            wait(NULL);
        }
    }
    return 0;
}